﻿using AutoMapper;
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Zj.OpenAuth.Domain.Core;
using Zj.OpenAuth.DTO.Common;
using Zj.OpenAuth.Repository.Models;

namespace Zj.OpenAuth.Mvc.Controllers
{
    public class TestsController : Controller
    {
        private readonly IMediator _mediator;
        public TestsController(IMediator mediator)
        {
            _mediator = mediator;
        }
        // GET: Tests
        public async Task<ActionResult> Index()
        {
            var user = new UserDTO() { Account = "Super", Password = "p@ssw0rd" };
            var cmd = new CreateUserCmd() { User = user };
            await _mediator.Send(cmd);
            return View();
        }
    }

    public class CreateUserCmd
        : IRequest<UserDTO>
    {
        public UserDTO User { get; set; }
    }

    public class CreateUserCmdHandler
        : IRequestHandler<CreateUserCmd, UserDTO>
    {
        public Task<UserDTO> Handle(CreateUserCmd request, CancellationToken cancellationToken)
        {
            var user = request.User;
            using (var db = new OpenAuthDbContext())
            {
                db.User.Add(Mapper.Map<UserDTO, User>(user));
            }
            return Task.FromResult(user);
        }
    }
}